package com.wlstock.funi.dao;
/**
 * Created by admin on 16/6/14.
 */

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.maxleap.FindCallback;
import com.maxleap.MLObject;
import com.maxleap.MLQuery;
import com.maxleap.MLQueryManager;
import com.maxleap.exception.MLException;
import com.wlstock.funi.model.StrategyFundModel;
import com.wlstock.funi.utils.TimeUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class StrategyFundSelDao {

    private DataBaseHelper dbHelper;
    private static StrategyFundSelDao daoInstance;
    private Dao<StrategyFundModel, Integer> dao;

    @SuppressWarnings("unchecked")
    private StrategyFundSelDao(Context mContext) {
        try {
            dbHelper = DataBaseHelper.getHelper(mContext);
            dao = dbHelper.getDao(StrategyFundModel.class);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static StrategyFundSelDao getInstance(Context mContext) {
        if (daoInstance == null) {
            synchronized (StrategyFundSelDao.class) {
                if (daoInstance == null) {
                    daoInstance = new StrategyFundSelDao(mContext);
                }
            }
        }
        return daoInstance;
    }


    private StrategyFundSelDao() {
    }

    public void createOrUpdate(StrategyFundModel model){
        try {
            dao.createOrUpdate(model);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<StrategyFundModel> queryAll(){
        try {
            return dao.queryBuilder().orderBy("createTime", false).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  new ArrayList<StrategyFundModel>();
    }

    public int deleteAll() {
        try {
            int effectRows = dao.updateRaw("delete from StrategyFundModel");
            return effectRows;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }


    public int queryShouldKeepDays(String stkCode) {
        try {
            String[] result = dao.queryRaw("select highYearKeepDays from StrategyFundModel where stkNo = ? order by createTime desc", stkCode).getFirstResult();
            if (result!=null && result.length > 0 ){
                return Integer.valueOf(result[0]);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 8888;
    }

    /**
     * 根据代码查询最新策略
     * @param stkCode
     * @return
     */
    public StrategyFundModel queryStraModelWithCode(String stkCode) {
        StrategyFundModel strategyFundModel = null;
//        List<StrategyFundModel> stocks = null;
        try {
//            stocks = dao.queryBuilder().orderBy("createTime", false).orderBy("highYearPecentage",false).where().eq("stkNo", stkCode).query();
            strategyFundModel = dao.queryBuilder().orderBy("createTime", false).orderBy("highYearPecentage",false).where().eq("stkNo", stkCode).queryForFirst();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return strategyFundModel;
    }

    /**
     * 查询近Offset天的策略选股
     * @param date
     * @param offset
     * @return
     */
    public List<StrategyFundModel> queryStraByOffsetDays(Date date, int offset) {
        Date startDate = TimeUtils.getDateByDayOffset(date, offset);
        List<StrategyFundModel> query = new ArrayList<StrategyFundModel>();
        try {
             query = dao.queryBuilder().orderBy("createTime", false).orderBy("highYearPecentage", false).groupBy("stkName").where().gt("createTime", startDate).and().ne("stkName","无数据").query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }


    public void sysFromServer(){
        MLQuery<MLObject> query = MLQuery.getQuery(StrategyFundModel.class.getSimpleName());
        query.orderByDescending("createdAt");
        MLQueryManager.findAllInBackground(query, new FindCallback<MLObject>() {
            @Override
            public void done(List<MLObject> list, MLException e) {
                if (e == null){
                    for(MLObject mlObject : list){
                        StrategyFundModel strategyFundModel = new StrategyFundModel();
                        strategyFundModel.setValuesFromMlOjb(mlObject);
                        StrategyFundSelDao.this.createOrUpdate(strategyFundModel);
                    }
                }
            }
        });
    }

    /**
     * 查询最新的一个可以买入的股,按照年化最高的来排列
     * 之后可以返回一个列表,然后对这个列表上的股票进行当天的打分之类
     * 最终筛选一个
     * @param date
     * @param offset
     * @return
     */
    public StrategyFundModel queryBuyModelByOffsetDays(Date date, int offset) {
        if (date == null || offset < 0){
            return null;
        }
        List<StrategyFundModel> models = queryStraByOffsetDays(date, offset);
        if (models!=null && !models.isEmpty()){
            return models.get(0);
        }
        return null;
    }
}